package cs236369.webserver;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

import javax.xml.bind.Marshaller.Listener;

import org.apache.http.params.BasicHttpParams;

public class WebServer {
	public static SessionMap sessionMap = new SessionMap();
	private Config config;
	private SocketReaderThread[] socketReaderThreads;
	private RequestHandlerThread[] requestHandlerThreads;
	private Queue<Request> requestQueue;
	private Queue<Socket> socketQueue;

	public WebServer(InputStream _config) throws Exception {
		config = new Config(_config);
		socketReaderThreads = new SocketReaderThread[config.socketReaders];
		requestHandlerThreads = new RequestHandlerThread[config.requestHandlers];
		requestQueue = new Queue<Request>(config.requestQueueSize);
		socketQueue = new Queue<Socket>(config.socketQueueSize);
	}

	public void init() throws IOException {
		BasicHttpParams params = new BasicHttpParams();
		for (int i = 0; i < config.socketReaders; i++) {
			socketReaderThreads[i] = new SocketReaderThread(socketQueue,requestQueue,params,config);
		}
		for (int i = 0; i < config.requestHandlers; i++) {
			requestHandlerThreads[i] = new RequestHandlerThread(requestQueue, config);
		}
	}

	public void start() {
		BasicHttpParams params = new BasicHttpParams();
		for (int i = 0; i < config.socketReaders; i++) {
			socketReaderThreads[i].start();
		}
		for (int i = 0; i < config.requestHandlers; i++) {
			requestHandlerThreads[i].start();
		}
		ConnectionListener listener = null;
		try {
			 listener = new ConnectionListener(Integer.parseInt(config.port), params, socketQueue);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		listener.start();
	}

	public static void main(String[] args) throws Exception {
		WebServer srv = new WebServer(new FileInputStream("config.xml"));
		srv.init();
		srv.start();
	}
}